<?php

class WSB_View_Helper_HtmlTable
{

	private $_id;
    private $_view;
	private $_rowset;
	private $_columns;
	private $_fields;
	private $_settings;
	private $_isObject;

	/**
	 * Erzeugt eine HTML-Tabelle mit clientseitiger Sortierung.
	 *
	 * @param Iterator|array $rowset
	 * @param array $columns
	 * @param array $fields
	 * @param array $settings
	 * @return string
	 */
    public function htmlTable($rowset, array $columns, array $fields, array $settings=array())
	{

    	// Javasripte hinzufuegen
    	$javascripts = array(
			'http://yui.yahooapis.com/2.7.0/build/yahoo-dom-event/yahoo-dom-event.js',
			'http://yui.yahooapis.com/2.7.0/build/element/element-beta-min.js',
			'http://yui.yahooapis.com/2.7.0/build/datasource/datasource-min.js',
			'http://yui.yahooapis.com/2.7.0/build/datatable/datatable-min.js'
    	);
    	foreach($javascripts AS $src) {
    		$this->_view->headScript()->offsetSetFile($src, $src);
    	}

    	// Stylesheets hinzufuegen
    	$stylesheets = array(
			'http://yui.yahooapis.com/2.7.0/build/datatable/assets/skins/sam/datatable.css',
			WSB_URL . 'WSB/design/default/skin/default/css/yui-dt-table.css'
    	);
    	foreach($stylesheets AS $link) {
    		$this->_view->headLink()->offsetSetStylesheet($link, $link);
    	}

		$this->_id = $this->_getId();
		$this->_rowset = $rowset;
		$this->_columns = $columns;
		$this->_fields = $fields;
		$this->_settings = $settings;
		$this->_isObject = $rowset instanceof Iterator;

		// Das Objekt wird an das Viewscript zurueckgegeben.
		// Das Viewscript gibt dieses via echo aus, dabi wird
		// die __toString() Methode aufgerufen.
		return $this;

    }

    /**
     * Ueberprueft, ob eine Referenz zu einem JS-File schon besteht.
     *
     * @param string $src
     * @return boolean
     */
    /*
    private function _headScriptExists($src)
	{
    	$exists = false;
		foreach($this->_view->headScript()->getValue() AS $value) {
			if(isset($value->attributes['src'])) {
				if($src === $value->attributes['src']) {
					$exists = true;
					break;
				}
			}
		}
		return $exists;
    }
    */

    /**
     * Ueberprueft, ob ein Link zu einem Stylesheet schon besteht.
     *
     * @param string $src
     * @return boolean
     */
    /*
    private function _headLinkExists($src)
	{
    	$exists = false;
		foreach($this->_view->headLink()->getValue() AS $value) {
			if(isset($value->href)) {
				if($src === $value->href) {
					$exists = true;
					break;
				}
			}
		}
		return $exists;
    }
    */

    /**
     * Eine ID erzeugen. Diese wird im generierten HTML fuer die ID-Attribute genutzt.
     *
     * @return string
     */
    private function _getId()
	{
    	srand();
    	return rand();
    }

    /**
     * HTML-Tabelle ausgeben
     *
     */
    private function __toString()
	{

    	$html = '';

    	// Div, Table
    	$html .= '<div id="markup-' . $this->_id . '">';
    	$html .= '<table id="table-' . $this->_id . '" class="style-1">';

    	// Head
    	$html .= '<thead>';
    	$html .= '<tr>';
		foreach($this->_columns AS $column) {
			$label = isset($column['label']) ? $column['label'] : '';
			$html .= sprintf('<th>%s</th>', $label);
		}
    	$html .= '</tr>';
    	$html .= '</thead>';

    	// Body
    	$i = 0;
    	$html .= '<tbody>';
    	foreach($this->_rowset AS $row) {
    		$show = true;
    		if(isset($this->_settings['callback'])) {
				$show = call_user_func_array($this->_settings['callback'], array($row));
    		}
    		if($show) {
	    		$class = ($i % 2 == 0) ? ' class="even"' : ' class="odd"';
		    	$html .= '<tr' . $class . '>';
				foreach($this->_fields AS $field) {
					$key = $field['key'];
					$callback = isset($field['callback']) ? $field['callback'] : '';
					if(empty($callback)) {
						if($this->_isObject) {
							$value = $row->$key;
						} else {
							// SimpleXMLElement
							if(is_object($row)) {
								$value = $row->$key;
							} else {
								$value = $row[$key];
							}
						}
					} else {
						$value = call_user_func_array($callback, array($row));
					}
					$html .= sprintf('<td>%s</td>', $value);
				}
		    	$html .= '</tr>';
		    	$i++;
    		}
    	}
    	$html .= '</tbody>';

    	// Table, Div
    	$html .= '</table>';
    	$html .= '</div>';

    	$html .= '
			<script type="text/javascript">
			YAHOO.util.Event.addListener(window, "load", function()
	{
			    YAHOO.example.EnhanceFromMarkup = new function()
	{
			        var myColumnDefs = ' . Zend_Json::encode($this->_columns) . ';
			        this.myDataSource = new YAHOO.util.DataSource(YAHOO.util.Dom.get("table-' . $this->_id . '"));
			        this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
			        this.myDataSource.responseSchema = {
			            fields: ' . Zend_Json::encode($this->_fields) . '
			        };
			        this.myDataTable = new YAHOO.widget.DataTable("markup-' . $this->_id . '", myColumnDefs, this.myDataSource,
			                ' . Zend_Json::encode($this->_settings) . ');
			        };
				}
			);
			</script>
    	';
    	return $html;

    }

    /**
     * Setze View Objekt. Diese Methode wird beim ersten Instanzieren aufgerufen.
     *
     * @param Zend_View_Interface $view
     */
    public function setView(Zend_View_Interface $view)
    {
        $this->_view = $view;
    }

}
